<script lang="ts" setup>
import { tabPaneRootContextKey } from '@/tokens/tabs';
import { inject, onMounted, onUpdated, ref, nextTick, computed } from 'vue';
import { chatProps } from './chat';
import { MessageTypeEnum } from '@/enums';
import useStore from '@/store';
import { ElMessage, ElNotification } from 'element-plus';
import { Badge } from 'ant-design-vue';
import Common from '@/utils';
import useWindow from '@/hooks/useWindow';
defineOptions({ name: 'Chat' });
const props = defineProps(chatProps);
const chatRef = ref(null);
const { maximize, minimize, close, windowActive, active } = useWindow(props.window, chatRef);

const currentChatUser = ref({} as any);
const currentEmployee = ref({} as any);
const content = ref('');
const chatLinks = ref([] as any);
const organizations = ref([] as any);
const chatLinkLoading = ref(true);
const organizationLoading = ref(true);
const chatMessages = ref([] as any);
const showBox = ref(false);
const boxRef = ref(null);
const scrollbarRef = ref(null);
const showMessage = ref(true);
const showOrganization = ref(false);
const getChatLinks = (): void => {
  window.$api.chat.getChatLinks().then(res => {
    chatLinks.value = res.data;
    chatLinkLoading.value = false;
  });
};
const getChatEmployees = () => {
  window.$api.employee.getChatEmployees().then(res => {
    organizations.value = res.data;
    organizationLoading.value = false;
  });
};
const getChatMessages = async chatId => {
  await window.$api.chat.getChatMessages(chatId).then(res => {
    chatMessages.value = res.data;
    nextTick(() => {
      scrollbarRef.value.setScrollTop(boxRef.value.clientHeight);
    });
  });
};
const setChatMessageToRead = async chatId => {
  await window.$api.chat.setChatMessageToRead(chatId).then(res => {});
};
const handleClick = async item => {
  currentChatUser.value = item;
  content.value = '';
  showBox.value = true;
  await getChatMessages(item.chatId);
  await setChatMessageToRead(item.chatId);
  let obj = chatLinks.value.find(x => x.userId == item.userId);
  obj.noReadCount = 0;
};
const handleChatMousemove = async event => {
  if (currentChatUser.value.userId) {
    let obj = chatLinks.value.find(x => x.userId == currentChatUser.value.userId);
    if (obj) {
      if (obj.noReadCount > 0) await setChatMessageToRead(currentChatUser.value.chatId);
      obj.noReadCount = 0;
    }
  }
};
const handleClickEmployee = item => {
  currentEmployee.value = item;
};
const totalNoReadCount = computed(() => {
  return chatLinks.value.reduce((sum, e) => sum + Number(e.noReadCount || 0), 0);
});
useStore.chat.signalR.signalr.on(MessageTypeEnum[MessageTypeEnum.NewMessage], message => {
  setcurrentChatLink(message.senderId, message.message, message.chatedOn);
  if (currentChatUser.value.userId == message.senderId) {
    let chatMessage = { senderId: message.senderId, senderName: message.senderName, message: message.message, chatedOn: message.chatedOn };
    chatMessages.value.push(chatMessage);
  }
  nextTick(() => {
    if (currentChatUser.value.userId != null && currentChatUser.value.userId == message.senderId) {
      scrollbarRef.value.setScrollTop(boxRef.value.clientHeight);
    }
  });
});
const setcurrentChatLink = (userId, lastMessage, lastChatedOn, isCurrent = false) => {
  let obj = chatLinks.value.find(item => item.userId == userId);
  obj.lastMessage = lastMessage;
  obj.lastChatedOn = lastChatedOn;
  if (!isCurrent) {
    obj.noReadCount += 1;
  }
  chatLinks.value = chatLinks.value.filter(item => item.userId != obj.userId);
  chatLinks.value.splice(0, 0, obj);
};
const sendMessage = () => {
  let sendMessageRequest = {
    chatLinkId: currentChatUser.value.chatId,
    receiverId: currentChatUser.value.userId,
    messageType: MessageTypeEnum.NewMessage,
    message: content.value,
  };
  if (content.value == '') {
    ElMessage.error('内容不能为空!');
    return;
  }
  window.$api.chat.sendMessage(sendMessageRequest).then(res => {
    //getChatMessages(currentUser.value.Id);
    let chatMessage = { senderId: useStore.setting.userInfo.id, message: content.value, chatedOn: new Date() };
    chatMessages.value.push(chatMessage);
    content.value = '';
    setcurrentChatLink(currentChatUser.value.userId, chatMessage.message, chatMessage.chatedOn, true);
    nextTick(() => {
      scrollbarRef.value.setScrollTop(boxRef.value.clientHeight);
    });
  });
};
const handlesidestripclick = (type: string) => {
  if (type == 'message') {
    if (!showMessage.value) {
      getChatLinks();
      showMessage.value = true;
      showOrganization.value = false;
    }
  } else {
    if (!showOrganization.value) {
      getChatEmployees();
      showOrganization.value = true;
      showMessage.value = false;
    }
  }
};
const addChatLink = async () => {
  if (currentEmployee.value.userId == null) {
    ElMessage.error('此员工未绑定用户账号,暂不支持聊天!');
    return;
  }
  if (chatLinks.value != null) {
    let obj = chatLinks.value.find(item => item.userId == currentEmployee.value.userId);
    if (obj == null) {
      await window.$api.chat.addChatLink(currentEmployee.value.id).then(res => {
        obj = res.data;
      });
    }
    chatLinks.value = chatLinks.value.filter(item => item.userId != obj.userId);
    chatLinks.value.splice(0, 0, obj);
    currentChatUser.value = obj;
    showMessage.value = true;
    showOrganization.value = false;
    handleClick(obj);
  }
};
onMounted(() => {
  getChatLinks();
});
onUpdated(() => {});
</script>

<template>
  <div ref="chatRef" class="chat" @mousemove="handleChatMousemove" @mousedown="windowActive" v-drag v-show="!window.minimize" :style="{ 'z-index': active ? 10 : 1 }">
    <div class="chat-header">
      <div class="header-sidestrip"></div>
    </div>
    <div class="chat-serach">
      <el-input prefix-icon="Search" placeholder="搜索"></el-input>
    </div>
    <div class="chat_defaulbtn-wrapper">
      <div class="chat_defaulbtn" @click="minimize">
        <el-icon :size="16"><i-fluent-subtract-48-regular /></el-icon>
      </div>
      <div class="chat_defaulbtn" @click="maximize">
        <el-icon v-if="window.maximize" :size="16"><i-fluent-square-multiple-48-regular /></el-icon>
        <el-icon v-else :size="16"><i-fluent-square-48-regular /></el-icon>
      </div>
      <div class="chat_defaulbtn" @click="close">
        <el-icon :size="16">
          <i-fluent-dismiss-48-regular />
        </el-icon>
      </div>
    </div>
    <div class="chat-content">
      <div class="chat-sidestrip">
        <a-badge :count="totalNoReadCount" :overflowCount="99">
          <div @click="handlesidestripclick('message')" :class="[showMessage ? 'active' : '', 'chat-sidestrip-btn']">
            <el-icon :size="20" v-if="showMessage"><i-bi-chat-fill /></el-icon>
            <el-icon :size="20" style="color: #fff" v-else><i-bi-chat /></el-icon>
          </div>
        </a-badge>
        <div @click="handlesidestripclick('organization')" :class="[showOrganization ? 'active' : '', 'chat-sidestrip-btn']">
          <el-icon :size="25" v-if="showOrganization"><i-bi-people-fill /></el-icon>
          <el-icon :size="25" v-else><i-bi-people /></el-icon>
        </div>
      </div>
      <div class="chatTab" v-show="showOrganization">
        <div class="chat-contact" v-loading="organizationLoading">
          <el-scrollbar>
            <el-tree
              :data="organizations"
              :props="{
                children: 'children',
                label: 'name',
              }"
              default-expand-all
              highlight-current
              :expand-on-click-node="false"
            >
              <template #default="scope">
                <div class="custom-node">
                  <div v-if="scope.node.data.type != 2" style="padding: 10px 0px">{{ scope.node.label }}</div>
                  <div class="custom-node-employee-wrapper">
                    <div
                      v-for="item in scope.node.data.employees"
                      class="custom-node-employee"
                      @click="handleClickEmployee(item)"
                      :class="[currentEmployee.id == item.id ? 'active' : '', 'custom-node-employee']"
                    >
                      <el-avatar :src="item.attachmentPath" :size="30" fit="cover" shape="square" />
                      <span style="margin-left: 10px">{{ item.name }}({{ scope.node.label }})</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
        <div class="chat-box" v-show="currentEmployee.id">
          <div class="chat-box-employee">
            <el-avatar :src="currentEmployee.attachmentPath" :size="70" fit="cover" shape="square" />
            <div class="chat-box-employee-group">
              <span v-for="item in currentEmployee.organizationNames">{{ item }}</span>
            </div>
            <div class="chat-box-employee-one">
              <div>
                <div class="chat-box-employee-one-info">
                  <span>姓名:</span>
                  <span>{{ currentEmployee.name }}</span>
                </div>
                <div class="chat-box-employee-one-info">
                  <span>手机号码:</span>
                  <span>{{ currentEmployee.mobilePhone }}</span>
                </div>
                <div class="chat-box-employee-one-info">
                  <span>入职日期:</span>
                  <span>{{ Common.formatDate(currentEmployee.hireDate, 'yyyy-MM-dd') }}</span>
                </div>
                <div class="chat-box-employee-one-info">
                  <span>状态:</span>
                  <span>{{ currentEmployee.statusName }}</span>
                </div>
              </div>
            </div>
            <el-button type="success" @click="addChatLink">发送消息</el-button>
          </div>
        </div>
      </div>
      <div class="chatTab" v-show="showMessage">
        <div class="chat-contact" v-loading="chatLinkLoading">
          <el-scrollbar>
            <div v-for="item in chatLinks" @click="handleClick(item)" :class="[currentChatUser == null ? '' : currentChatUser.name == item.name ? 'active' : '', 'chat-contact-item']">
              <div class="chat-contact-item-avatar">
                <a-badge :count="item.noReadCount" :overflow-count="99">
                  <el-avatar :src="item.attachmentPath" :size="45" fit="cover" shape="square" />
                </a-badge>
              </div>

              <div class="chat-contact-item-content">
                <div class="chat-contact-item-content-line">
                  <span class="chat-contact-item-link">{{ item.name }}</span>
                  <span class="chat-contact-item-time">
                    {{ Common.weChatTimeFormat(item.lastChatedOn) }}
                  </span>
                </div>
                <div class="chat-contact-item-message">
                  {{ item.lastMessage }}
                  <span></span>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div class="chat-box" v-if="showBox">
          <div class="chat-current">
            <span>{{ currentChatUser.name }}</span>
          </div>
          <el-scrollbar ref="scrollbarRef">
            <div class="chat-box-content" ref="boxRef">
              <div v-for="item in chatMessages" class="chat-box-content-item">
                <div class="chat-box-content-item-time">
                  <span>{{ Common.weChatTimeFormat(item.chatedOn) }}</span>
                </div>
                <div v-if="item.senderId === useStore.setting.userInfo.id" class="chat-box-content-item-content current">
                  <div>{{ item.message }}</div>
                  <el-avatar :src="useStore.setting.userInfo.attachmentPath" :size="35" fit="cover" shape="square" />
                </div>
                <div v-else class="chat-box-content-item-content others">
                  <el-avatar :src="currentChatUser.attachmentPath" :size="35" fit="cover" shape="square" />
                  <div>{{ item.message }}</div>
                </div>
              </div>
            </div>
          </el-scrollbar>
          <div class="chat-box-input">
            <el-input :rows="4" type="textarea" v-model="content" />
            <el-button type="success" text bg @click="sendMessage">发送</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<style lang="scss">
.chat {
  position: fixed;
  .custom-node {
    .custom-node-employee-wrapper {
      font-size: 14px;
      color: #000;
      .custom-node-employee {
        display: flex;
        align-items: center;
        height: 40px;
        padding: 2px 5px;
        border-radius: 5px;
        &:hover {
          background: #dddddd;
        }
        &.active {
          background: #c9c8c8;
        }
      }
    }
  }
  // .el-tree-node__content > .el-tree-node__expand-icon {
  //   display: none;
  // }
  .el-tree-node__content {
    height: auto;
    align-items: baseline;
  }
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: none;
  }
  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    background: none;
  }
  .el-tree-node:focus > .el-tree-node__content {
    background: none;
  }
  .el-tree-node__content:hover {
    background: none;
  }
  .el-textarea__inner {
    min-height: 31px;
    box-shadow: none;
    border-top: 1px solid #ececec;
    resize: none;
    border-radius: 0px;
    outline: none;
    &:hover {
      box-shadow: none;
    }
    &:focus {
      box-shadow: none;
    }
  }
  .ant-badge-count {
    box-shadow: none;
  }
}
</style>
<style scoped lang="scss">
.chat {
  .el-tree {
    background: none;
  }
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f5f5f5;
  width: 100%;
  height: 100%;
  .chat-header {
    height: 50px;
    width: 100%;
    flex-shrink: 0;
    .header-sidestrip {
      width: 50px;
      background: #2a2e32;
      height: 100%;
    }
  }
  .chat-content {
    flex: 1;
    display: flex;
    width: 100%;
    overflow: hidden;
    .chatTab {
      flex: 1;
      display: flex;
    }
    .chat-contact {
      background: #e6e5e5;
      user-select: none;
      width: 250px;
      height: 100%;
      .chat-contact-item {
        display: flex;
        align-items: center;
        padding: 10px;
        .chat-contact-item-avatar {
          display: flex;
          margin-right: 10px;
        }
        .chat-contact-item-content {
          display: flex;
          justify-content: space-between;
          flex-direction: column;
          align-items: flex-start;
          flex: 1;
          overflow: hidden;
          .chat-contact-item-content-line {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
          }
          .chat-contact-item-message {
            font-size: 12px;
            color: #999999;
            padding-top: 2px;
            width: 100%;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
          }
          .chat-contact-item-link {
            font-size: 15px;
            margin-bottom: 5px;
          }
          .chat-contact-item-time {
            color: #999999;
            font-size: 12px;
            padding-bottom: 4px;
          }
        }
        .chat-contact-item-tips {
          color: #c45656;
        }
        &:hover {
          background: #dddddd;
        }
        &.active {
          background: #c9c8c8;
        }
      }
    }
    .chat-box {
      flex: 1;
      height: 100%;
      display: flex;
      flex-direction: column;
      border-top: 1px solid #ececec;
      overflow: hidden;
      .chat-box-input {
        position: relative;
        height: 95px;
        .el-button {
          position: absolute;
          right: 0;
          bottom: 0;
          width: 80px;
        }
      }
      .chat-box-content {
        margin: 5px 0px;
        flex: 1;
        .chat-box-content-item {
          .chat-box-content-item-time {
            display: flex;
            justify-content: center;
            span {
              background: #dadada;
              color: #fff;
              font-size: 12px;
              border-radius: 2px;
              padding: 3px;
            }
          }
          .chat-box-content-item-content {
            margin: 10px 0px;
            display: flex;
            padding: 10px 20px;
            > div {
              background: #fff;
              display: flex;
              align-items: center;
              padding: 6px 15px;
              border-radius: 5px;
              word-wrap: break-word;
              word-break: break-all;
              box-sizing: border-box;
              text-align: left;
              margin-left: 10px;
              max-width: 60%;
            }
            &.current {
              justify-content: flex-end;
              > div {
                background: #9eeb6b;
                margin-left: 0px;
                margin-right: 10px;
              }
            }
          }
        }
      }
    }
    .chat-sidestrip {
      width: 50px;
      background: #2a2e32;
      color: #ececec;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 20px;
      .chat-sidestrip-btn {
        margin-bottom: 20px;
        cursor: pointer;
        &.active {
          color: #07c160;
        }
      }
    }
  }
  .chat-serach {
    position: absolute;
    left: 50px;
    top: 0;
    width: 250px;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-right: 1px solid #ececec;
    .el-input {
      width: 80%;
      height: 30px;
    }
  }
  .chat-current {
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    left: 320px;
    top: 0;
  }
  .chat_defaulbtn-wrapper {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    height: 25px;
    .chat_defaulbtn {
      width: 35px;
      display: flex;
      justify-content: center;
      align-items: center;
      &:hover {
        background: #e9e9eb;
      }
      &:last-child {
        // border-top-right-radius: 5px;
        &:hover {
          color: #fff;
          background: #c45656;
        }
      }
    }
  }
  .chat-box-employee {
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100%;
    justify-content: center;
    .chat-box-employee-group {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 20px;
      span {
        margin-bottom: 10px;
        &:last-child {
          margin-bottom: 0px;
        }
      }
    }
    .chat-box-employee-one {
      display: flex;
      flex-direction: column;
      font-size: 16px;
      color: #999999;
      margin-bottom: 10px;
      .chat-box-employee-one-info {
        display: flex;
        margin-bottom: 10px;
        & span:first-child {
          width: 70px;
          margin-right: 10px;
          text-align: right;
        }
        & span:last-child {
          flex: 1;
        }
      }
    }
  }
}
</style>
